﻿using System;
using System.Collections.Generic;
using System.Linq;
using KLS.PPDS.Core.Entity;
using KLS.PPDS.Data.Database.Repository.EntityRepository;
using KLS.PPDS.Resources;
using KLS.PPDS.Utilities;
using KLS.PPDS.Utility;

namespace KLS.PPDS.ApplicationService.Manager
{
    public class UserManager:RepositoryManager<UserRepository>
    {
        public static User Get(string username)
        {
            var repoManager = RepositoryManager<UserRepository>.Repository;
            return repoManager.FindAll().ToList().Where(c => c.UserName.ToLower().Equals(username.ToLower()) && c.IsDeleted==false).FirstOrDefault();
        }


        public static IList<User> GetUsersByRoleName(string role, int? companyId)
        {
            return Repository.GetUserByRoleName(role, companyId);
        }


        
        public static string Validate(User user) 
        {

            if (user.RoleId.HasValue && CommonSession.IsUserSuperAdmin) 
            {
                if (!RoleManager.IsSuperadminOrGraphicsRole(user.RoleId.Value) ) 
                {
                    if (!user.CompanyId.HasValue) 
                    {
                        return CommonMessage.SelectCompany;
                    }                    
                }
            }
            
            var id = user.Id;
            var userReporitory = RepositoryManager<UserRepository>.Repository;

            if (id == 0)
            {
                var tmp = userReporitory.GetUserByName(user.UserName);
                if (tmp != null && tmp.Id > 0 )
                {
                    if (tmp.IsDeleted) 
                    {
                        return (CommonMessage.UserExistsButDeleted);
                    }
                    
                    return CommonMessage.UserExists;
                }                                
            }
            return String.Empty;
        }

        public static void Save(User user)
        {

            var id = user.Id;
            var userReporitory = RepositoryManager<UserRepository>.Repository;

            //if role = superadmin or graphics
            if (user.RoleId.HasValue && user.RoleId.Value > 0) 
            {
                var role = RoleManager.GetRoleById(user.RoleId.Value);
                if (role.RoleName == CommonConstant.Graphics || role.RoleName == CommonConstant.Superadmin)
                {
                    user.CompanyId = null;
                }
            }
            


            //if(id==0)
            {
                var tmp = userReporitory.GetUserByName(user.UserName);
                if (tmp != null && tmp.Id.Equals(user.Id).Equals(false))
                {
                    throw new Exception(CommonMessage.UserExists);
                }
            }

            user.InitAudit();
          
           userReporitory.SaveAndEvict(user);
           
           if (id == 0)
           {
               LogManager.LogDbAdd(user);   
           }
           else
           {
               LogManager.LogDbUpdate(user); 
           }
        }

        public static void Update(User user)
        {
            user.InitAudit();
            var userReporitory = RepositoryManager<UserRepository>.Repository;
            userReporitory.Update(user);
           
        }

        public static int CheckDuplicateDeletedUser(User user, int companyId)
        {
            var userReporitory = RepositoryManager<UserRepository>.Repository;
            var validUser = userReporitory.FindAll().Where(u => u.UserName == user.UserName && u.IsDeleted == true).FirstOrDefault();
            if (validUser!=null &&  validUser.Id>0)
            {
            //    var userGroupReporitory = RepositoryManager<UserGroupRelRepository>.Repository();
            //    //var groupReporitory = RepositoryManager<GroupRepository>.Repository();
            //    var UserGroupByuser = userGroupReporitory.FindAll().Where(ug => ug.UserId == validUser.UserId).FirstOrDefault();
            //    //var Group = groupReporitory.FindAll().Where(g => g.CompanyId == companyId).FirstOrDefault();

            //    if (UserGroupByuser != null)
            //    {
            //        if (UserGroupByuser.Group.CompanyId == companyId)
            //        {
            //            validUser.Deleted = false;                        
            //            validUser.LanguageId = user.LanguageId;
            //            validUser.Password = user.Password;
            //            validUser.PhoneNo = user.PhoneNo;
            //            validUser.UpdatedBy = user.UpdatedBy;                        
            //            validUser.UpdatedDate = user.UpdatedDate;                        
            //            validUser.UserFullName = user.UserFullName;
            //            validUser.DepartmentId = user.DepartmentId;
            //            userReporitory.SaveAndEvict(validUser);

            //            return validUser.UserId;
            //        }
            //    }
            }
            return 0;
        }






        public static List<User> GetAll()
        {
           
            return Repository.GetAll();
        }
        
        public static IList<User> GetAllByComapanyId(int ?CompanyId)
        {


            if(CommonSession.IsUserSuperAdmin)
            {
                if (CompanyId == null || CompanyId.GetValueOrDefault(0) == 0)
                {
                    return GetAll();
                }

                return Repository.GetAllUserByComapnyId(CompanyId.GetValueOrDefault(0));

            }

            //Edit will only get Journalist for editing
            if (CommonSession.IsUserEditor)
            {
                return Repository.GetUserByRoleName(CommonConstant.Journalist, CommonSession.CompanyId);
            }


            return null;
            // return Repository.FindAll().Where(c => c.CompanyId == CompanyId.Value).OrderBy(c=>c.UserName).ToList();
        }


        public static User Get(int userid)
        {
            var repoManager = RepositoryManager<UserRepository>.Repository;
            return repoManager.FindAll().Where(c => c.Id.Equals(userid)).FirstOrDefault();
        }


        public static List<User> GetUsers(int companyId)
        {
           
            return Repository.FindAll().ToList();
        }




        public static bool Delete(int userid)
        {
            var user = Repository.FindOne(userid);
            if (user != null) 
            {
                user.IsDeleted = true;
                // uniqe prefix added  with deleted userName
                user.UserName = Guid.NewGuid()+"_"+user.UserName;
                user.InitAudit();
                Repository.Update(user);
                LogManager.LogDbDelete(user);
            }
            
            return false;
        }
       
    }
  
}
